package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }


    @Override
    public TradeVo orderTradeData() {
        // 获取当前登录用户的id（从安全上下文）
        Long userId = SecurityContextHolder.getUserId();

        // 远程调用购物车服务获取已勾选商品列表
        R<List<CartInfo>> cartInfoListResult = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);

        // 检查远程调用是否失败
        if (R.FAIL == cartInfoListResult.getCode()) {
            throw new ServiceException(cartInfoListResult.getMsg());
        }

        // 获取购物车数据
        List<CartInfo> cartInfoList = cartInfoListResult.getData();

        // 校验购物车是否有选中商品
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("购物车无选中商品");
        }

        // 初始化订单项列表和总金额
        List<OrderItem> orderItemList = null;
        BigDecimal totalAmount = new BigDecimal(0);

        // 转换购物车数据为订单项
        if (!CollectionUtils.isEmpty(cartInfoList)) {
            //stream().map()将CartInfo流转换为OrderItem流
            orderItemList = cartInfoList.stream().map(cartInfo -> {
                OrderItem orderItem = new OrderItem();
                // 属性拷贝（浅拷贝）
                BeanUtils.copyProperties(cartInfo, orderItem);
                // 单独设置价格字段
                orderItem.setSkuPrice(cartInfo.getSkuPrice());
                return orderItem;
            }).collect(Collectors.toList());

            // 计算订单总金额
            for(OrderItem orderItem : orderItemList) {
                // 金额 = 单价 × 数量
                totalAmount = totalAmount.add(
                        orderItem.getSkuPrice().multiply(
                                new BigDecimal(orderItem.getSkuNum())
                        )
                );
            }
        }

        // 生成防重提交的流水号
        String tradeNo = this.getTradeNo(userId);

        // 构建返回对象
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);       // 设置总金额
        tradeVo.setOrderItemList(orderItemList);   // 设置订单项列表
        tradeVo.setTradeNo(tradeNo);               // 设置流水号
        return tradeVo;//返回视图数据
    }

   /* private String generateTradeNo(Long userId) {// 生成防重提交的流水号
        // 构建Redis键：user:tradeNo:{userId}
        String userTradeKey = "user:tradeNo:" + userId;

        // 生成UUID作为流水号（移除连字符）
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");

        // 将流水号存入Redis（有效期5分钟）
        redisTemplate.opsForValue().set(
                userTradeKey,
                tradeNo,
                5,
                TimeUnit.MINUTES
        );

        return tradeNo;
    }
*/

    //专业生成流水号
    private  String getTradeNo(Long userId) {
        String tradeNoKey = "user:trade:"+userId;
        String tradeNo = UUID.randomUUID().toString().replaceAll("-","");
        //订单流水号保存到redis中，5分钟有效。可以用于去重。
        redisTemplate.opsForValue().set(tradeNoKey,tradeNo,5, TimeUnit.MINUTES);
        return tradeNo;
    }



    //用户提交订单
    @Override
    public Long submitOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId(); //从线程上获取

        //1.去重
        String tradeNoKey = "user:trade:"+userId;// 构建Redis键
        String tradeNoFromForm = orderForm.getTradeNo();//获取订单流水号，从自定义方法获取
        //思路：提交表单订单流水号  和  redis中的订单流水号  比较？   一致则进行下面业务处理；否则，提示不能重复提交表单。
/*        String tradeNoFromForm = orderForm.getTradeNo();
        String tradeNoKey = "user:trade:"+userId;
        String tradeNoFromRedis = (String)redisTemplate.opsForValue().get(tradeNoKey);
        if(!tradeNoFromForm.equals(tradeNoFromRedis)){
            throw new ServiceException("不能重复提交表单");
        }
        redisTemplate.delete(tradeNoKey);*/ //代码不是原子性的。不能用于业务开发。

        //使用LUA脚本保证原子性。
        String script = "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "   return redis.call('del',KEYS[1])\n" +
                "else\n" +
                "   return 0\n" +
                "end";
        //DefaultRedisScript用于执行lua脚本，传入两个参数lua脚本和返回值类型
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        //redisTemplate.execute执行lua脚本
        //Arrays.asList()这个方法接受一个数组作为参数，并将其转换为一个 List（列表）
        //tradeNoKey = "user:trade:"+userId;用于构建Redis键      tradeNoFromForm订单流水号


        //Redis 脚本执行：
        //Redis 会解析 redisScript 中的 Lua 脚本。
        //使用 tradeNoKey 作为 KEYS[1]，检查 Redis 中是否存在对应的键。
        //使用 tradeNoFromForm 作为 ARGV[1]，与 Redis 中键的值比较。
        //结果返回：
        //如果键存在且值匹配，删除键并返回 1（Long 类型）。
        //否则返回 0（Long 类型）。
        Long result = (Long)redisTemplate.execute(redisScript, Arrays.asList(tradeNoKey),tradeNoFromForm);
        if(result==0){
            throw new ServiceException("不能重复提交表单");
        }

        //2.验空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();//获取结算商品列表
        if(CollectionUtils.isEmpty(orderItemList)){//CollectionUtils.isEmpty用于检查集合是否为空
            throw new ServiceException("数据不能为空");
        }

        //3.校验价格是否一致，如果不一致则更新价格,取消下单
        //// map()转换元素,接收一个函数作为参数，该函数会被应用到每个元素上，并将其映射成一个新的元素。
        //OrderItem::getSkuId提取所有商品ID,toList()收集为列表
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        //远程调用商品服务获取最新价格
        R<List<SkuPrice>> skuPriceListR = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListR.getCode()){// 调用失败处理
            throw new ServiceException(skuPriceListR.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListR.getData();
        // 将价格列表转为Map<skuId, price>便于查找
        Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceList
                .stream()//将列表转换为流（Stream）
                .collect(//对流进行终止操作，将流中的元素收集到某个集合中
                        Collectors.toMap(// 使用Collectors.toMap收集器，将流中的元素转换为Map
                                SkuPrice::getSkuId,// 键的提取函数：从SkuPrice对象中提取skuId作为键
                                SkuPrice::getSalePrice));// 值的提取函数：从SkuPrice对象中提取salePrice作为值
        // 检查价格是否变动
        StringBuilder builder = new StringBuilder();
        for (OrderItem orderItem : orderItemList) {
            // 比较订单价格和最新价格
            if(orderItem.getSkuPrice().compareTo(skuIdToSalePriceMap.get(orderItem.getSkuId())) != 0){
                builder.append("【"+orderItem.getSkuName()+"】商品价格有变动;");
            }
        }
        if(StringUtils.hasText(builder.toString())){
            //更新购物车商品价格
            remoteCartService.updateCartPrice(userId,SecurityConstants.INNER);
            throw new ServiceException(builder.toString());
        }

        //4.检查与锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map((orderItem)->{
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).toList();
        R<String> stringR = remoteProductService.checkAndLock(tradeNoFromForm, skuLockVoList, SecurityConstants.INNER);
        if(R.FAIL == stringR.getCode()){
            throw new ServiceException(stringR.getMsg());
        }
        String data = stringR.getData();
        if(StringUtils.hasText(data)){
            throw new ServiceException(data);
        }

        //5.保存订单(order_info\order_item\order_log)
        Long orderId = null;
        try {
            orderId = saveOrder(orderForm);
        } catch (Exception e) {

            // 下单异常，解锁库存。
            //4.1 下单失败，解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderForm.getTradeNo());

            throw new ServiceException("下单失败");
        }

        //6.删除购物车商品。考虑一下：可以在支付后删除购物车勾选的商品。否则，下单取消，还得把商品加回购物车。
        remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);

        //7.发送延迟消息。指定支付等待时间，如果不支付，消费者处理延迟消息就会自动取消订单，解锁库存。
        rabbitService.sendDealyMessage(MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                String.valueOf(orderId), MqConst.CANCEL_ORDER_DELAY_TIME);
        return orderId;
    }



    //辅助方法：保存订单
    private Long saveOrder(OrderForm orderForm) {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        //1.保存订单数据
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        // 获取用户收货地址
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        // 设置收货信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        // 计算订单金额
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            // 单项金额 = 单价 × 数量
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        // 设置金额相关字段
        orderInfo.setTotalAmount(totalAmount); //实付总价格 (减掉优惠钱 + 运费的钱)
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount); //商品总价格(不包括优惠卷和运费)
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0); //订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
        //orderInfo.setCreateTime(new Date());
        orderInfoMapper.insert(orderInfo); //主键回填

        Long orderId = orderInfo.getId();// 获取生成的订单ID

        //2.保存订单项数据
        //List<OrderItem> orderItemList = orderForm.getOrderItemList();
        orderItemList.forEach(orderItem -> {
            orderItem.setOrderId(orderId);
            orderItemMapper.insert(orderItem); //性能优化 - 批量保存
        });

        //3.保存订单日志数据
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setProcessStatus(0); //订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLogMapper.insert(orderLog);
        return orderId;
    }


    @Transactional
    @Override
    public void processCloseOrder(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if(orderInfo != null && orderInfo.getOrderStatus().intValue() == 0){ //延迟消息到了，还没有付款，关单
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("超时未付款系统自动关单");
            orderInfoMapper.updateById(orderInfo);

            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderId);
            orderLog.setProcessStatus(-1); //订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
            orderLog.setNote("系统取消订单");
            orderLog.setOperateUser("系统");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }


    //根据订单号获取订单信息
    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }


    @Transactional
    @Override
    public void processPaySucess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getOrderNo, orderNo).select(OrderInfo::getId, OrderInfo::getOrderStatus));
        //未支付
        if(orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }
}